#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <string.h>
#include "esp_log.h"
#include "lcd1602.h"
#include "time.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_sntp.h"
#include "esp_netif_sntp.h"

#define ESP_I2C_PORT    I2C_NUM_0
#define ESP_I2C_SDA     21 //GPIO_NUM_21
#define ESP_I2C_SCL     22 //GPIO_NUM_22
#define ESP_I2C_ADDRESS 0x27 //LCD1602_I2C_ADRESS_ALTERNATE

//#define ESP_WIFI_SSID      "HAOHAO_2.4G"
//#define ESP_WIFI_PASS      "tangfeifei@1981"
#define ESP_WIFI_SSID      "Pangu_guest"
#define ESP_WIFI_PASS      "Pangu2016"

#define ESP_MAXIMUM_RETRY  5

#define WIFI_CONNECTED_BIT BIT0
#define WIFI_FAIL_BIT      BIT1

#define SNTP_TIME_SERVER   "ntp.ntsc.ac.cn"


static EventGroupHandle_t s_wifi_event_group;

static int s_retry_num = 0;

static lcd1602_context *lcd_display;

static void lcd_log(int row, char* text, int delay)
{
    lcd1602_set_cursor(lcd_display, row, 0);
    lcd1602_string(lcd_display, text);
    lcd1602_set_display(lcd_display, true, false, true);

    vTaskDelay(delay);
}

#define ESP_ERROR_CHECK_DISPLAY(x) do {                                 \
        esp_err_t err_rc_ = (x);                                        \
        if (unlikely(err_rc_ != ESP_OK)) {                              \
            char _esp_err_msg[64];                                    \
            sprintf(_esp_err_msg, "error[%d]", err_rc_);                        \
            lcd_log(1, _esp_err_msg, 100);                                      \
            _esp_error_check_failed(err_rc_, __FILE__, __LINE__,        \
                                    __ASSERT_FUNC, #x);                 \
        }                                                               \
    } while(0)



static void event_handler(void* arg, esp_event_base_t event_base,
                                int32_t event_id, void* event_data)
{
    if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
        esp_wifi_connect();
    } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
        if (s_retry_num < ESP_MAXIMUM_RETRY) {
            char _msg[64]; // yyyy-MM-dd
            sprintf(_msg, " - try %d", s_retry_num);
            lcd_log(1, _msg, 300);

            esp_wifi_connect();

            s_retry_num++;            
        } else {
            xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT);
        }

        lcd_log(1, "connect fail", 100);
    } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
        ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;

        char _msg[64]; // yyyy-MM-dd
        sprintf(_msg, IPSTR, IP2STR(&event->ip_info.ip));
        lcd_log(1, _msg, 100);

        s_retry_num = 0;
        xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
    }
}


void wifi_init(void)
{
    if (NULL == lcd_display)
        return;

    lcd1602_clear(lcd_display);

    lcd_log(0, "connect wifi:", 100);

    s_wifi_event_group = xEventGroupCreate();
    
    lcd_log(1, "step0", 100);
    ESP_ERROR_CHECK(esp_netif_init());

    lcd_log(1, "step1", 100);

    ESP_ERROR_CHECK(esp_event_loop_create_default());
    esp_netif_create_default_wifi_sta();

    lcd_log(1, "step2", 100);

    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    
    lcd_log(1, "step3", 100);

    ESP_ERROR_CHECK_DISPLAY(esp_wifi_init(&cfg));

    lcd_log(1, "step4", 100);

    esp_event_handler_instance_t instance_any_id;
    esp_event_handler_instance_t instance_got_ip;
    ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,
                                                        ESP_EVENT_ANY_ID,
                                                        &event_handler,
                                                        NULL,
                                                        &instance_any_id));
    ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT,
                                                        IP_EVENT_STA_GOT_IP,
                                                        &event_handler,
                                                        NULL,
                                                        &instance_got_ip));

    wifi_config_t wifi_config = {
        .sta = {
            .ssid = ESP_WIFI_SSID,
            .password = ESP_WIFI_PASS,
            /* Authmode threshold resets to WPA2 as default if password matches WPA2 standards (pasword len => 8).
             * If you want to connect the device to deprecated WEP/WPA networks, Please set the threshold value
             * to WIFI_AUTH_WEP/WIFI_AUTH_WPA_PSK and set the password with length and format matching to
             * WIFI_AUTH_WEP/WIFI_AUTH_WPA_PSK standards.
             */
            .threshold.authmode = WIFI_AUTH_WPA2_PSK,
            .sae_pwe_h2e = WPA3_SAE_PWE_BOTH,
            .sae_h2e_identifier = "ESP32Board",
        },
    };
    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA) );
    ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config) );

    lcd_log(1, "step start...", 100);
    ESP_ERROR_CHECK(esp_wifi_start() );

    lcd1602_clear(lcd_display);
    lcd_log(0, "wifi finished.", 100);

    /* Waiting until either the connection is established (WIFI_CONNECTED_BIT) or connection failed for the maximum
     * number of re-tries (WIFI_FAIL_BIT). The bits are set by event_handler() (see above) */
    EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group,
            WIFI_CONNECTED_BIT | WIFI_FAIL_BIT,
            pdFALSE,
            pdFALSE,
            portMAX_DELAY);

    /* xEventGroupWaitBits() returns the bits before the call returned, hence we can test which event actually
     * happened. */
    if (bits & WIFI_CONNECTED_BIT) {
        lcd_log(1, "SUCCESS.       ", 100);
    } else if (bits & WIFI_FAIL_BIT) {
        lcd_log(1, "FAILED.        ", 100);
    } else {
        lcd_log(1, "UNEXPECTED.    ", 100);
    }
}

void sntp_sync(void)
{
    if (NULL == lcd_display)
        return;

    lcd1602_clear(lcd_display);

    lcd_log(0, "sync time:", 100);

    esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG(SNTP_TIME_SERVER);

    config.start = false;                       // start SNTP service explicitly (after connecting)
    config.server_from_dhcp = true;             // accept NTP offers from DHCP server, if any (need to enable *before* connecting)
    config.renew_servers_after_new_IP = true;   // let esp-netif update configured SNTP server(s) after receiving DHCP lease
    config.index_of_first_server = 1;           // updates from server num 1, leaving server 0 (from DHCP) intact

    config.ip_event_to_renew = IP_EVENT_STA_GOT_IP;

    esp_netif_sntp_init(&config);

    lcd_log(1, "SNTP START.    ", 100);
    
    ESP_ERROR_CHECK_DISPLAY(esp_netif_sntp_start());

    struct timeval tv_now;
    gettimeofday(&tv_now, NULL);

    esp_netif_sntp_deinit();
}

int lcd_hello() 
{
    if (NULL == lcd_display)
    {
        return 1;
    }

    lcd1602_string(lcd_display, "SIMPLE CLOCK");
    lcd1602_set_cursor(lcd_display, 1, 0);
    lcd1602_string(lcd_display, " by Handsome:)");

    lcd1602_set_display(lcd_display, true, false, true);

    vTaskDelay(500);

    return ESP_OK;
}

void lcd_clock(void) 
{
    if (NULL == lcd_display)
        return;

    // 清屏
    lcd1602_clear(lcd_display);

    time_t t;
    struct tm *now;    
    
    t = time(NULL);
    now = localtime(&t);
    
    char _date[64]; // yyyy-MM-dd
    sprintf(_date, "%4d-%02d-%02d", now->tm_year + 1900, now->tm_mon + 1, now->tm_mday);
    char _time[64]; // HH:mm:ss
    sprintf(_time, "%02d:%02d:%02d", now->tm_hour, now->tm_min, now->tm_sec);

    // 日期
    lcd1602_set_cursor(lcd_display, 0, 0);
    lcd1602_string(lcd_display, _date);

    // 时间
    lcd1602_set_cursor(lcd_display, 1, 0);
    lcd1602_string(lcd_display, _time);

    lcd1602_set_display(lcd_display, true, false, true);

    vTaskDelay(100);
}

void app_main(void)
{
    // 初始化
    lcd1602_lowlevel_config config;
    config.port = ESP_I2C_PORT;
    config.pin_sda = ESP_I2C_SDA;
    config.pin_scl = ESP_I2C_SCL;
    
    lcd_display = lcd1602_init(ESP_I2C_ADDRESS, true, &config);

    lcd_hello();

    wifi_init();
    sntp_sync();

    setenv("TZ", "CST-8", 1);
    tzset();

    while(1) 
    {
        lcd_clock();
    }

    lcd1602_deinit(lcd_display);

    

   for(;;)
      vTaskDelay(portMAX_DELAY);
}
